﻿using System;
using System.Collections.Generic;
using System.Net;

namespace PLC
{
    /// <summary>
    /// PLC工厂
    /// </summary>
    public class PLCFactory
    {
        private static Dictionary<PLCType, Type> plcTypes = new Dictionary<PLCType, Type>
        {
            { PLCType.OmronFinsTCP, typeof(OmronFinsTCP) },
            { PLCType.OmronCipNet, typeof(OmronCipNet) },
          
            
            //{ PLCType.Mitsubishi, typeof(MitsubishiPLC) },
            // 添加其他 PLC 类型和对应的类...
        };

        public static PlcReadWriteBase CreatePLC(PLCType type, int pid, string pname, IPEndPoint iep, int timeout = 10)
        {
            if (!plcTypes.TryGetValue(type, out Type plcType))
            {
                throw new ArgumentException($"不支持的 PLC 类型: {type}");
            }

            try
            {
                return (PlcReadWriteBase)Activator.CreateInstance(plcType, pid, pname, iep, timeout);
            }
            catch (Exception ex)
            {
                throw new Exception($"创建 PLC 类型时出错 {type}", ex);
            }
        }

        public static PlcReadWriteBase CreatePLC(string typeName, int pid, string pname, IPEndPoint iep, int timeout = 10)
        {
            if (!Enum.TryParse(typeName, true, out PLCType type))
            {
                throw new ArgumentException($"PLC 类型名称无效: {typeName}");
            }

            return CreatePLC(type, pid, pname, iep, timeout);
        }
    }
}
